package com.qianguo.shop.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;

import com.eva.androidlibrary.icon.TypefaceManager;
import com.qianguo.shop.R;

/**
 * @author eva
 * @date 15/11/20
 */
public class IconFontTextView extends TextView {

    private IconFont mIcon = null;

    public IconFontTextView(Context context) {
        super(context);
        init(context, null);
    }

    public IconFontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public IconFontTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public IconFontTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        if (attrs == null) {
            return;
        }

        int iconFontResId = -1;
        int unicode = 0x0;
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IconFontTextView);
        final String iconFontResIdName = a.getString(R.styleable.IconFontTextView_iconfont_typeface);
        if (iconFontResIdName != null) {
            iconFontResId = getResources().getIdentifier(
                    iconFontResIdName, "raw", context.getPackageName());
        }
        if (iconFontResId <= 0) {
            iconFontResId = R.raw.iconfont;
        }
        String unicodeStr = a.getString(R.styleable.IconFontTextView_iconfont_icon);
        if (!TextUtils.isEmpty(unicodeStr)) {
            if (unicodeStr.startsWith("0x")) {
                unicodeStr = unicodeStr.substring(2);
            }
            unicode = Integer.valueOf(unicodeStr, 16);
        }
        a.recycle();

        setTypeface(TypefaceManager.IconicTypeface
                .getInstance(iconFontResId).getTypeface(context));
        if (unicode != 0x0) {
            setIcon(unicode);
        }
    }

    public void setIcon(int unicode) {
        setIcon(new IconFont(unicode));
    }

    public void setIcon(IconFont icon) {
        mIcon = icon;
        final char[] txt = Character.toChars(mIcon.getIconUnicode());
        setText(new String(txt, 0, txt.length));
    }

    public IconFont getIcon() {
        return mIcon;
    }

    public static class IconFont {

        private int mIconFontUnicode = 0;

        public IconFont(int unicode) {
            mIconFontUnicode = unicode;
        }

        public int getIconUnicode() {
            return mIconFontUnicode;
        }
    }
}
